<template>
  <div
    class="login-container"
    :style="`height:${view.height}px;background:${
      isDark ? '#1B1B1F' : '#fff'
    };`"
  >
    <el-card class="login-card" :style="`height:${680}px;`">
      <el-image
        style="height: 100%; width: calc(100%); position: relative"
        :src="cardLeft"
        :fit="'contain'"
      />

      <div class="login-form">
        <div class="logo-title">
          <el-image
            style="width: 40px; height: 40px"
            :src="logo"
            alt="Element logo"
            fit="scale-down"
          />
          <h1>灌区灌溉动态遥感监测系统</h1>
        </div>
        <el-card class="box-card">
          <h2 style="text-align: center; margin-bottom: 20px">用户登录</h2>
          <el-form
            ref="ruleFormRef"
            style="max-width: 100%; height: 400px"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="auto"
            class="login-rule-form"
          >
            <el-form-item label="帐号" prop="username">
              <el-input
                size="large"
                clearable
                v-model.number="ruleForm.username"
              />
            </el-form-item>
            <el-form-item
              label="密码"
              prop="password"
              style="padding-top: 10px"
            >
              <el-input
                size="large"
                v-model="ruleForm.password"
                type="password"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item>
              <div class="btn-container">
                <el-button
                  type="primary"
                  @click="submitForm(ruleFormRef)"
                  size="large"
                  style="width: 100px"
                >
                  登录
                </el-button>
                <el-button
                  @click="resetForm(ruleFormRef)"
                  size="large"
                  style="width: 100px"
                >
                  取消
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, reactive, ref, onMounted } from "vue";
import { useDark, useToggle } from "@vueuse/core";
import cardLeft from "@/assets/login/card_left.png";
import logo from "@/assets/logo/logo.png";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import router from "@/router";
import HttpService from "@/api/api"; // Assuming you have a global API service setup
 import { useSubsystemStore } from "@/store/subsystem";
  
let isDark = ref(useDark());
const toggleDark = useToggle(isDark);
const subsystemStore = useSubsystemStore();
const ruleFormRef = ref<FormInstance>();

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else {
    callback();
  }
};

const validateUserName = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入登录密码"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  username: "wilson",
  password: "3635",
});

const rules = reactive<FormRules<typeof ruleForm>>({
  password: [{ validator: validatePass, trigger: "blur" }],
  username: [{ validator: validateUserName, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      const params = {
        username: ruleForm.username,
        password: ruleForm.password,
      };
      HttpService.auth.login(
        params,
        (res) => {
          if (res.status === 200 && res.data.success == true) {
            // On success, save the token and navigate to a protected page
            localStorage.setItem("authToken", res.data.data.accessToken); // Example token storage
            ElMessage.success("登录成功");
            router.push("/index/general/algorithmManage/algorithmList"); // Redirect to a protected page
            console.log(res.data.data)
            subsystemStore.setSubsystem(res.data.data.user.subsystemId);
            subsystemStore.setRole(res.data.data.user.roleId)
            subsystemStore.setUser(res.data.data.user)
          } else {
            ElMessage.error(res.message || "用户名或密码错误");
          }
        },
        (error) => {
          ElMessage.error("登录失败，请稍后再试");
        }
      );
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

var view = reactive({
  height: window.innerHeight,
});
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-card {
  overflow: hidden;
  border-radius: 10px;
  width: 1500px;
}
</style>

<style lang="scss">
.login-card {
  .el-card__body {
    padding: 0;
    position: relative;

    .login-form {
      width: 550px;
      height: 100%;
      background: #1d1e1f;
      position: absolute;
      z-index: 1000;
      left: 0;
      top: 0;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .logo-title {
        display: flex;

        h1 {
          margin-bottom: 40px;
          font-size: 27px;
          margin-left: 10px;
          font-weight: 500;
        }
      }

      .box-card {
        width: 400px;
        box-shadow: none;
        border: none;

        h2 {
        }

        .el-card__body {
          padding: 0;
          margin-top: 20px;

          .login-rule-form {
            width: 100%;
            padding: 0 20px;

            .btn-container {
              display: flex;
              justify-content: center;
              width: 100%;
              padding-top: 20px;
            }
          }
        }
      }
    }
  }
}
</style>
